import Strophe from "./sdk/libs/strophe";
import xmldom from "./sdk/libs/xmldom/dom-parser";
import websdk from "./sdk/connection";
import config from "WebIMConfig";

console.group = console.group || {};
console.groupEnd = console.groupEnd || {};

var window = {};
let WebIM = window.WebIM = websdk;
window.WebIM.config = config;
var DOMParser = window.DOMParser = xmldom.DOMParser;
let document = window.document = new DOMParser().parseFromString("<?xml version='1.0'?>\n", "text/xml");

if (WebIM.config.isDebug) {

  function ts() {
    var d = new Date();
    var Hours = d.getHours(); // 获取当前小时数(0-23)
    var Minutes = d.getMinutes(); // 获取当前分钟数(0-59)
    var Seconds = d.getSeconds(); // 获取当前秒数(0-59)
    return (Hours < 10 ? "0" + Hours : Hours) + ":" + (Minutes < 10 ? "0" + Minutes : Minutes) + ":" + (Seconds < 10 ? "0" + Seconds : Seconds) + " ";
  }

  Strophe.Strophe.log = function(level, msg) {
    // console.log(ts(), level, msg);
  };

  Strophe.Strophe.Connection.prototype.rawOutput = function(data) {
    try {
      console.group("%csend # " + ts(), "color: blue; font-size: large");
      console.log("%c" + data, "color: blue");
      console.groupEnd();
    } catch (e) {
      console.log(e);
    }
  };
}

/**
 * Set autoSignIn as true (autoSignInName and autoSignInPwd are configured below),
 * You can auto signed in each time when you refresh the page in dev model.
 */
WebIM.config.autoSignIn = false;
if (WebIM.config.autoSignIn) {
  WebIM.config.autoSignInName = "lwz2";
  WebIM.config.autoSignInPwd = "1";
}


// var stropheConn = new window.Strophe.Connection("ws://im-api.easemob.com/ws/", {
//                 inactivity: 30,
//                 maxRetries: 5,
//                 pollingTime: 4500
//             });
//
// stropheConn.connect(
//   '$t$' + 'YWMtmbQEBKKIEeaGmMtXyg5n1wAAAVlkQvGO2WOJGlMCEJKM4VV9GCMnb_XLCXU',
//   function() {
//     console.log(arguments, 'ggogogo');
//   }, stropheConn.wait, stropheConn.hold);
WebIM.parseEmoji = function(msg) {
  if (typeof WebIM.Emoji === "undefined" || typeof WebIM.Emoji.map === "undefined") {
    return msg;
  }
  var emoji = WebIM.Emoji,
    reg = null;
  var msgList = [];
  var objList = [];
  for (var face in emoji.map) {
    if (emoji.map.hasOwnProperty(face)) {
      while (msg.indexOf(face) > -1) {
        msg = msg.replace(face, "^" + emoji.map[face] + "^");
      }
    }
  }
  var ary = msg.split("^");
  var reg = /^e.*g$/;
  for (var i = 0; i < ary.length; i++) {
    if (ary[i] != "") {
      msgList.push(ary[i]);
    }
  }
  for (var i = 0; i < msgList.length; i++) {
    if (reg.test(msgList[i])) {
      var obj = {};
      obj.data = msgList[i];
      obj.type = "emoji";
      objList.push(obj);
    } else {
      var obj = {};
      obj.data = msgList[i];
      obj.type = "txt";
      objList.push(obj);
    }
  }
  console.log(objList);
  return objList;

};

WebIM.time = function() {
  var date = new Date();
  var Hours = date.getHours();
  var Minutes = date.getMinutes();
  var Seconds = date.getSeconds();
  var time = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " +
    (Hours < 10 ? "0" + Hours : Hours) + ":" + (Minutes < 10 ? "0" + Minutes : Minutes) + ":" + (Seconds < 10 ? "0" + Seconds : Seconds);
  return time;
};

WebIM.Emoji = {
  path: "../../../../../images/faces/",
  map: {
    "[):]": "ee_1.png",
    "[:D]": "ee_2.png",
    "[;)]": "ee_3.png",
    "[:-o]": "ee_4.png",
    "[:p]": "ee_5.png",
    "[(H)]": "ee_6.png",
    "[:@]": "ee_7.png",
    "[:s]": "ee_8.png",
    "[:$]": "ee_9.png",
    "[:(]": "ee_10.png",
    "[:'(]": "ee_11.png",
    "[<o)]": "ee_12.png",
    "[(a)]": "ee_13.png",
    "[8o|]": "ee_14.png",
    "[8-|]": "ee_15.png",
    "[+o(]": "ee_16.png",
    "[|-)]": "ee_17.png",
    "[:|]": "ee_18.png",
    "[*-)]": "ee_19.png",
    "[:-#]": "ee_20.png",
    "[^o)]": "ee_21.png",
    "[:-*]": "ee_22.png",
    "[8-)]": "ee_23.png",
    "[del]": "btn_del.png",
    "[(|)]": "ee_24.png",
    "[(u)]": "ee_25.png",
    "[(S)]": "ee_26.png",
    "[(*)]": "ee_27.png",
    "[(#)]": "ee_28.png",
    "[(R)]": "ee_29.png",
    "[({)]": "ee_30.png",
    "[(})]": "ee_31.png",
    "[(k)]": "ee_32.png",
    "[(F)]": "ee_33.png",
    "[(W)]": "ee_34.png",
    "[(D)]": "ee_35.png"
  }
};

WebIM.EmojiObj = {
  // 相对 emoji.js 路径
  path: "../../../../../images/faces/",
  map1: {
    "[):]": "ee_1.png",
    "[:D]": "ee_2.png",
    "[;)]": "ee_3.png",
    "[:-o]": "ee_4.png",
    "[:p]": "ee_5.png",
    "[(H)]": "ee_6.png",
    "[:@]": "ee_7.png"
  },
  map2: {
    "[:s]": "ee_8.png",
    "[:$]": "ee_9.png",
    "[:(]": "ee_10.png",
    "[:'(]": "ee_11.png",
    "[<o)]": "ee_12.png",
    "[(a)]": "ee_13.png",
    "[8o|]": "ee_14.png"
  },
  map3: {
    "[8-|]": "ee_15.png",
    "[+o(]": "ee_16.png",
    "[|-)]": "ee_17.png",
    "[:|]": "ee_18.png",
    "[*-)]": "ee_19.png",
    "[:-#]": "ee_20.png",
    "[del]": "del.png"
  },
  map4: {
    "[^o)]": "ee_21.png",
    "[:-*]": "ee_22.png",
    "[8-)]": "ee_23.png",
    "[(|)]": "ee_24.png",
    "[(u)]": "ee_25.png",
    "[(S)]": "ee_26.png",
    "[(*)]": "ee_27.png"
  },
  map5: {
    "[(#)]": "ee_28.png",
    "[(R)]": "ee_29.png",
    "[({)]": "ee_30.png",
    "[(})]": "ee_31.png",
    "[(k)]": "ee_32.png",
    "[(F)]": "ee_33.png",
    "[(W)]": "ee_34.png",
    "[(D)]": "ee_35.png"
  },
  map6: {
    "[del]": "del.png"
  }
};

// wx.connectSocket({url: WebIM.config.xmppURL, method: "GET"})

WebIM.conn = new WebIM.connection({
  isMultiLoginSessions: WebIM.config.isMultiLoginSessions,
  https: typeof WebIM.config.https === "boolean" ? WebIM.config.https : location.protocol === "https:",
  url: WebIM.config.xmppURL,
  apiUrl: WebIM.config.apiURL,
  isAutoLogin: false,
  heartBeatWait: WebIM.config.heartBeatWait,
  autoReconnectNumMax: WebIM.config.autoReconnectNumMax,
  autoReconnectInterval: WebIM.config.autoReconnectInterval
});
WebIM.conn.listen({
  onOpened: function(message) { //连接成功回调
    // 如果isAutoLogin设置为false，那么必须手动设置上线，否则无法收消息
    // 手动上线指的是调用conn.setPresence(); 如果conn初始化时已将isAutoLogin设置为true
    // 则无需调用conn.setPresence();             
  },
  onClosed: function(message) {}, //连接关闭回调
  onTextMessage: function(message) {}, //收到文本消息
  onEmojiMessage: function(message) {}, //收到表情消息
  onPictureMessage: function(message) {}, //收到图片消息
  onCmdMessage: function(message) {}, //收到命令消息
  onAudioMessage: function(message) {}, //收到音频消息
  onLocationMessage: function(message) {}, //收到位置消息
  onFileMessage: function(message) {}, //收到文件消息
  onVideoMessage: function(message) {
    var node = document.getElementById('privateVideo');
    var option = {
      url: message.url,
      headers: {
        'Accept': 'audio/mp4'
      },
      onFileDownloadComplete: function(response) {
        var objectURL = WebIM.utils.parseDownloadResponse.call(conn, response);
        node.src = objectURL;
      },
      onFileDownloadError: function() {
        console.log('File down load error.')
      }
    };
    WebIM.utils.download.call(conn, option);
  }, //收到视频消息
  onPresence: function(message) {}, //处理“广播”或“发布-订阅”消息，如联系人订阅请求、处理群组、聊天室被踢解散等消息
  onRoster: function(message) {}, //处理好友申请
  onInviteMessage: function(message) {}, //处理群组邀请
  onOnline: function() {}, //本机网络连接成功
  onOffline: function() {}, //本机网络掉线
  onError: function(message) {}, //失败回调
  onBlacklistUpdate: function(list) { //黑名单变动
    // 查询黑名单，将好友拉黑，将好友从黑名单移除都会回调这个函数，list则是黑名单现有的所有好友信息
    console.log(list);
  },
  onReceivedMessage: function(message) {}, //收到消息送达服务器回执
  onDeliveredMessage: function(message) {}, //收到消息送达客户端回执
  onReadMessage: function(message) {}, //收到消息已读回执
  onCreateGroup: function(message) {}, //创建群组成功回执（需调用createGroupNew）
  onMutedMessage: function(message) {} //如果用户在A群组被禁言，在A群发消息会走这个回调并且消息不会传递给群其它成员
});

// async response
// WebIM.conn.listen({
//   onOpened: () => dispatch({
//     type: Types.ON_OPEND
//   })
// })

// export default WebIM;
module.exports = {
  "default": WebIM
};